package com.guigu.eduservice.config;

/**
 * @Author: janecraft
 * @Date: 2025/6/28
 * @Description: com.guigu.aclservice.config
 * @Version： 1.0
 */

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @Author: janecraft
 * @Date: 2025/5/19
 * @Description: com.guigu.demo.config
 * @Version： 1.0
 */
// 所有的配置类都必须加 @Configuration
// 该配置类相当于 原来的配置文件, .xml
@Configuration
public class RedisConfig {

    // @Bean 注解，相当于 <bean id="s" class="com.bean.Student"></bean>
    // 方法的返回值就是class类型， 默认的方法名就是对象在spring容器中的名字
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);

        // 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
        Jackson2JsonRedisSerializer<Object> jacksonSerial = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.activateDefaultTyping(om.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL);
        jacksonSerial.setObjectMapper(om);

        // 使用StringRedisSerializer来序列化和反序列化redis的key值
        StringRedisSerializer stringSerial = new StringRedisSerializer();
        // key采用String的序列化方式
        template.setKeySerializer(stringSerial);
        // hash的key也采用String的序列化方式
        template.setHashKeySerializer(stringSerial);
        // value序列化方式采用jackson
        template.setValueSerializer(jacksonSerial);
        // hash的value序列化方式采用jackson
        template.setHashValueSerializer(jacksonSerial);
        template.afterPropertiesSet();

        return template;
    }
}
